/**
 * 中空领航应用 - 引导式访问说明组件
 * 为应用各页面提供首次访问的引导说明功能
 */

class GuideSystem {
    constructor() {
        this.currentStep = 0;
        this.steps = [];
        this.isActive = false;
        this.pageKey = '';
    }

    /**
     * 初始化引导系统
     * @param {string} pageKey - 页面唯一标识
     * @param {Array} steps - 引导步骤配置
     */
    init(pageKey, steps) {
        this.pageKey = pageKey;
        this.steps = steps;
        
        // 检查是否是首次访问
        if (this.isFirstVisit(pageKey)) {
            this.createGuideContainer();
            this.isActive = true;
            this.showStep(0);
            
            // 标记已访问
            this.markAsVisited(pageKey);
        }
    }
    
    /**
     * 检查是否是首次访问
     * @param {string} pageKey - 页面唯一标识
     * @returns {boolean} - 是否是首次访问
     */
    isFirstVisit(pageKey) {
        return !localStorage.getItem(`guide_visited_${pageKey}`);
    }
    
    /**
     * 标记页面已访问
     * @param {string} pageKey - 页面唯一标识
     */
    markAsVisited(pageKey) {
        localStorage.setItem(`guide_visited_${pageKey}`, 'true');
    }
    
    /**
     * 重置引导状态（用于测试）
     * @param {string} pageKey - 页面唯一标识，如果不提供则重置所有页面
     */
    resetGuideStatus(pageKey = null) {
        if (pageKey) {
            localStorage.removeItem(`guide_visited_${pageKey}`);
        } else {
            // 获取所有localStorage键
            for (let i = 0; i < localStorage.length; i++) {
                const key = localStorage.key(i);
                if (key.startsWith('guide_visited_')) {
                    localStorage.removeItem(key);
                }
            }
        }
    }
    
    /**
     * 创建引导容器
     */
    createGuideContainer() {
        // 创建主容器
        const container = document.createElement('div');
        container.className = 'guide-container';
        container.id = 'guideContainer';
        
        // 创建遮罩层
        const overlay = document.createElement('div');
        overlay.className = 'guide-overlay';
        overlay.id = 'guideOverlay';
        
        // 创建提示框
        const tooltip = document.createElement('div');
        tooltip.className = 'guide-tooltip';
        tooltip.id = 'guideTooltip';
        
        // 创建按钮容器
        const buttonContainer = document.createElement('div');
        buttonContainer.className = 'guide-buttons';
        
        // 创建跳过按钮
        const skipButton = document.createElement('button');
        skipButton.className = 'guide-button guide-skip';
        skipButton.textContent = '跳过';
        skipButton.addEventListener('click', () => this.endGuide());
        
        // 创建下一步按钮
        const nextButton = document.createElement('button');
        nextButton.className = 'guide-button guide-next';
        nextButton.textContent = '下一步';
        nextButton.addEventListener('click', () => this.nextStep());
        
        // 组装DOM
        buttonContainer.appendChild(skipButton);
        buttonContainer.appendChild(nextButton);
        tooltip.appendChild(buttonContainer);
        container.appendChild(overlay);
        container.appendChild(tooltip);
        document.body.appendChild(container);
        
        // 添加样式
        this.addStyles();
    }
    
    /**
     * 添加引导样式
     */
    addStyles() {
        const styleElement = document.createElement('style');
        styleElement.textContent = `
            .guide-container {
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                z-index: 10000;
                pointer-events: none;
            }
            
            .guide-overlay {
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background-color: rgba(0, 0, 0, 0.7);
                pointer-events: auto;
            }
            
            .guide-highlight {
                position: absolute;
                box-shadow: 0 0 0 9999px rgba(0, 0, 0, 0.7);
                border-radius: 4px;
                pointer-events: none;
                z-index: 10001;
            }
            
            .guide-tooltip {
                position: absolute;
                background: linear-gradient(135deg, #0B3D91, #4A90E2);
                color: white;
                padding: 15px;
                border-radius: 8px;
                max-width: 80%;
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
                z-index: 10002;
                pointer-events: auto;
                animation: tooltip-appear 0.3s ease-out;
            }
            
            @keyframes tooltip-appear {
                from {
                    opacity: 0;
                    transform: translateY(10px);
                }
                to {
                    opacity: 1;
                    transform: translateY(0);
                }
            }
            
            .guide-tooltip:before {
                content: '';
                position: absolute;
                width: 12px;
                height: 12px;
                background: #0B3D91;
                transform: rotate(45deg);
            }
            
            .guide-tooltip.position-bottom:before {
                top: -6px;
                left: 20px;
            }
            
            .guide-tooltip.position-top:before {
                bottom: -6px;
                left: 20px;
                background: #4A90E2;
            }
            
            .guide-tooltip.position-left:before {
                top: 20px;
                right: -6px;
                background: #4A90E2;
            }
            
            .guide-tooltip.position-right:before {
                top: 20px;
                left: -6px;
            }
            
            .guide-title {
                font-weight: bold;
                font-size: 16px;
                margin-bottom: 8px;
            }
            
            .guide-content {
                font-size: 14px;
                margin-bottom: 15px;
            }
            
            .guide-buttons {
                display: flex;
                justify-content: space-between;
            }
            
            .guide-button {
                padding: 8px 15px;
                border: none;
                border-radius: 4px;
                font-weight: bold;
                cursor: pointer;
            }
            
            .guide-skip {
                background-color: rgba(255, 255, 255, 0.2);
                color: white;
            }
            
            .guide-next {
                background-color: #FFD700;
                color: #0B3D91;
            }
            
            .guide-done {
                background-color: #FFD700;
                color: #0B3D91;
                width: 100%;
            }
        `;
        document.head.appendChild(styleElement);
    }
    
    /**
     * 显示指定步骤
     * @param {number} index - 步骤索引
     */
    showStep(index) {
        if (index >= this.steps.length || !this.isActive) {
            this.endGuide();
            return;
        }
        
        this.currentStep = index;
        const step = this.steps[index];
        
        // 获取目标元素
        const targetElement = document.querySelector(step.target);
        if (!targetElement) {
            console.error(`引导目标元素未找到: ${step.target}`);
            this.nextStep();
            return;
        }
        
        // 创建高亮区域
        this.createHighlight(targetElement);
        
        // 更新提示框内容和位置
        this.updateTooltip(step, targetElement);
        
        // 更新按钮文本
        this.updateButtons(index);
    }
    
    /**
     * 创建高亮区域
     * @param {Element} targetElement - 目标元素
     */
    createHighlight(targetElement) {
        // 移除旧的高亮区域
        const oldHighlight = document.querySelector('.guide-highlight');
        if (oldHighlight) {
            oldHighlight.remove();
        }
        
        // 获取元素位置信息
        const rect = targetElement.getBoundingClientRect();
        
        // 创建高亮元素
        const highlight = document.createElement('div');
        highlight.className = 'guide-highlight';
        highlight.style.width = `${rect.width + 8}px`;
        highlight.style.height = `${rect.height + 8}px`;
        highlight.style.left = `${rect.left - 4}px`;
        highlight.style.top = `${rect.top - 4}px`;
        
        // 添加到容器
        document.getElementById('guideContainer').appendChild(highlight);
    }
    
    /**
     * 更新提示框内容和位置
     * @param {Object} step - 步骤配置
     * @param {Element} targetElement - 目标元素
     */
    updateTooltip(step, targetElement) {
        const tooltip = document.getElementById('guideTooltip');
        const rect = targetElement.getBoundingClientRect();
        
        // 清除旧的位置类
        tooltip.className = 'guide-tooltip';
        
        // 设置提示框内容
        tooltip.innerHTML = `
            <div class="guide-title">${step.title || '提示'}</div>
            <div class="guide-content">${step.content}</div>
            <div class="guide-buttons">
                <button class="guide-button guide-skip">跳过</button>
                <button class="guide-button guide-next">
                    ${this.currentStep === this.steps.length - 1 ? '完成' : '下一步'}
                </button>
            </div>
        `;
        
        // 重新绑定事件
        tooltip.querySelector('.guide-skip').addEventListener('click', () => this.endGuide());
        tooltip.querySelector('.guide-next').addEventListener('click', () => this.nextStep());
        
        // 计算提示框位置
        const position = step.position || 'bottom';
        tooltip.classList.add(`position-${position}`);
        
        const tooltipRect = tooltip.getBoundingClientRect();
        const margin = 10; // 与目标元素的间距
        
        // 根据位置设置提示框坐标
        switch (position) {
            case 'top':
                tooltip.style.left = `${rect.left + (rect.width / 2) - (tooltipRect.width / 2)}px`;
                tooltip.style.top = `${rect.top - tooltipRect.height - margin}px`;
                break;
            case 'bottom':
                tooltip.style.left = `${rect.left + (rect.width / 2) - (tooltipRect.width / 2)}px`;
                tooltip.style.top = `${rect.bottom + margin}px`;
                break;
            case 'left':
                tooltip.style.left = `${rect.left - tooltipRect.width - margin}px`;
                tooltip.style.top = `${rect.top + (rect.height / 2) - (tooltipRect.height / 2)}px`;
                break;
            case 'right':
                tooltip.style.left = `${rect.right + margin}px`;
                tooltip.style.top = `${rect.top + (rect.height / 2) - (tooltipRect.height / 2)}px`;
                break;
        }
        
        // 确保提示框不超出屏幕
        const viewportWidth = window.innerWidth;
        const viewportHeight = window.innerHeight;
        
        if (parseFloat(tooltip.style.left) < 10) {
            tooltip.style.left = '10px';
        } else if (parseFloat(tooltip.style.left) + tooltipRect.width > viewportWidth - 10) {
            tooltip.style.left = `${viewportWidth - tooltipRect.width - 10}px`;
        }
        
        if (parseFloat(tooltip.style.top) < 10) {
            tooltip.style.top = '10px';
        } else if (parseFloat(tooltip.style.top) + tooltipRect.height > viewportHeight - 10) {
            tooltip.style.top = `${viewportHeight - tooltipRect.height - 10}px`;
        }
    }
    
    /**
     * 更新按钮文本
     * @param {number} index - 当前步骤索引
     */
    updateButtons(index) {
        const nextButton = document.querySelector('.guide-next');
        if (nextButton) {
            if (index === this.steps.length - 1) {
                nextButton.textContent = '完成';
                nextButton.classList.add('guide-done');
                
                // 隐藏跳过按钮
                const skipButton = document.querySelector('.guide-skip');
                if (skipButton) {
                    skipButton.style.display = 'none';
                }
            } else {
                nextButton.textContent = '下一步';
                nextButton.classList.remove('guide-done');
                
                // 显示跳过按钮
                const skipButton = document.querySelector('.guide-skip');
                if (skipButton) {
                    skipButton.style.display = 'block';
                }
            }
        }
    }
    
    /**
     * 进入下一步
     */
    nextStep() {
        if (this.currentStep < this.steps.length - 1) {
            this.showStep(this.currentStep + 1);
        } else {
            this.endGuide();
        }
    }
    
    /**
     * 结束引导
     */
    endGuide() {
        if (!this.isActive) return;
        
        const container = document.getElementById('guideContainer');
        if (container) {
            // 添加淡出动画
            container.style.transition = 'opacity 0.3s ease';
            container.style.opacity = '0';
            
            // 动画结束后移除元素
            setTimeout(() => {
                container.remove();
            }, 300);
        }
        
        this.isActive = false;
    }
}

// 创建全局引导系统实例
const guideSystem = new GuideSystem();